package com.nidu.demo.tenant.executor.query;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.tenant.convertor.TenantConvertor;
import com.nidu.demo.tenant.dto.TenantCO;
import com.nidu.demo.tenant.gateway.TenantGateway;
import com.nidu.demo.tenant.model.Tenant;
import com.nidu.demo.user.gateway.UserGateway;
import com.nidu.demo.user.model.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 租户单查询执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class TenantSingleQryExe {

    private final TenantGateway gateway;

    private final TenantConvertor convertor;

    private final UserGateway userGateway;

    public SingleResponse<TenantCO> execute(Long id) {
        // 1. 查询数据
        Tenant tenant = gateway.getById(id);
        if(tenant == null){
            throw new BizException(ErrorCodeConstants.TENANT_NOT_FOUND.getCode(), ErrorCodeConstants.TENANT_NOT_FOUND.getMessage());
        }
        // 2. 转换为DTO返回
        TenantCO tenantCO = convertor.toClientObject(tenant);

        User user = userGateway.getById(tenantCO.getAdminId());
        tenantCO.setAdminName(user.getNickname());
        tenantCO.setAdminMobile(user.getMobile());
        return SingleResponse.of(tenantCO);
    }

    public SingleResponse<TenantCO> execute(String name) {
        // 1. 查询数据
        Tenant tenant = gateway.getByName(name);
        if(tenant == null){
            throw new BizException(ErrorCodeConstants.TENANT_NOT_FOUND.getCode(), ErrorCodeConstants.TENANT_NOT_FOUND.getMessage());
        }
        // 2. 转换为DTO返回
        TenantCO tenantCO = convertor.toClientObject(tenant);

        User user = userGateway.getById(tenantCO.getAdminId());
        tenantCO.setAdminName(user.getNickname());
        tenantCO.setAdminMobile(user.getMobile());
        return SingleResponse.of(tenantCO);
    }
}